<?php

namespace Addons\OaSystem\Model;
use Think\Model;
use AliyunMNS\Client;
use AliyunMNS\Model\BatchSmsAttributes;
use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Requests\PublishMessageRequest;
use AliyunMNS\Exception\MnsException;
use Qcloud\Sms\SmsSingleSender;
use Dysmsapi\Request\V20170525\SendSmsRequest;
/* use AliyunMNS\Client;
use AliyunMNS\Topic;
use AliyunMNS\Constants;
use AliyunMNS\Model\MailAttributes;
use AliyunMNS\Model\SmsAttributes;
use AliyunMNS\Model\BatchSmsAttributes;
use AliyunMNS\Model\MessageAttributes;
use AliyunMNS\Exception\MnsException;
use AliyunMNS\Requests\PublishMessageRequest; */


/**
 * Sms模型
 */
class SmsModel extends Model{
    var $config;
    //$from_type发送短信的用途 'card':会员卡手机认证
    function sendSms($to,$from_type){
        $this->config = getAddonConfig('Sms');
        if(strlen($to)!=11){
            $res['errcode'] = 0;
            $res['msg'] = "请检查手机号是否填写正确";
        }else{
            if($this->config ["type"] == 1){
                //云之讯
                $res = $this->_sendUcpassSms($to);
            }else if($this->config ["type"] == 2){
                $res = $this->_sendTencentSms($to);
            }else{
                $res['errcode'] = 0;
                $res['msg'] = "配置参数出错";
            }
        }
        return $res;
    }
    function checkSms($phone,$code){
        $this->config = getAddonConfig('Sms');
        $map['phone'] = $phone;
        $sms = M ( 'sms' )->where ($map)->order ( 'id desc' )->find ();
        if($sms && $code == $sms['code']){
            $expire = (int)($this->config['expire']);
            if(NOW - $sms['cTime']>expire*60){
                $res['errcode'] = '61451';
                $res['msg'] = "验证码已过期，请重新发送";
            }else{
                $res['errcode'] = 0;
                $res['msg'] = "验证码成功";
            }
        }else{
            $res['errcode'] = '61451';
            $res['msg'] = "验证失败";
        }
        return $res;
    }

    function _sendTencentSms($to){//腾讯云短信
        //$to是你要发送的手机号码
        //导入sdk
        require_once VENDOR_PATH ."SmsSender.php";
        //获取你的后台配置的那些参数
        $this->config = D ( 'Common/AddonConfig' )->get ( 'Sms' );
        $sign =$this->config["'sign'"];
        $templId =$this->config["'TtemplateId'"];
        // 请根据实际 appid 和 appkey 进行开发，以下只作为演示 sdk 使用
        //$appid = 1400034293;
        //$appkey = "27bef0f7d2d56e8bac6d3ce239d701dd";
        $appid =$this->config["'appid'"];
        $appkey =$this->config["'appkey'"];
        try {

            $singleSender = new \SmsSender\SmsSingleSender($appid, $appkey);
            //四位验证码
            $code =rand(0000,9999);
            $params[] = $code;
            $result = $singleSender->sendWithParam("86", $to, $templId, $params, $sign, "", "");
            $rsp = json_decode($result, true);
            //这里的data是我用来保存发送记录的
            $data['phone'] = $to;
            $data['plat_type'] = $this->config["'type'"];
            //$data['from_type'] = $from_type;
            $data['code'] = $code;
            $data['errcode'] = 0;
            $data['smsId'] = $rsp['sid'];
            $data['cTime'] = time();
            $this -> add($data);
            $res['errcode'] = 0;
            $res['msg'] = "发送成功";

        } catch (\Exception $e) {
            $res['errcode'] = -1;
            $res['msg'] = "发送失败,腾讯云短信接口访问失败！！";
        }

        return $res;
    }


    function getSign(){//腾讯云获取签名
        //生成sig
        $appid = 1400034293;
        $appkey = "27bef0f7d2d56e8bac6d3ce239d701dd";
        $strRand = rand(pow(10,9),pow(10,10)-1); //url中的random字段的值
        $param['time'] =$strTime = time(); //unix时间戳
        $param['sig'] =$sig = hash('sha256','appkey='.$appkey.'&random='.$strRand.'&time='.$strTime);
        $url ='https://yun.tim.qq.com/v5/tlssmssvr/add_sign?sdkappid='.$appid.'&random='.$strRand;

        $param['remark'] ='';
        $param['text'] ='圆梦云科技';

        $param =json_encode($param,JSON_UNESCAPED_UNICODE);

        $ch =curl_init();

        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$param);
        curl_setopt($ch,CURLOPT_HEADER,0);

        $res =curl_exec($ch);

        if(!$res){
            return curl_error($ch);
        }else{
            $res = json_decode($res,true);
            if($res['result'] == 0){
                //dump($res['data']['text']);exit;
                return $res['data']['text'];
            }else{
                //dump($res);exit;
                return false;
            }
        }

    }

    function getTemplate(){//腾讯云获取模板
        $appid = 1400034293;
        $appkey = "27bef0f7d2d56e8bac6d3ce239d701dd";
        $strRand = rand(pow(10,9),pow(10,10)-1); //url中的random字段的值
        $param['time'] =$strTime = time(); //unix时间戳
        $param['sig'] =$sig =hash('sha256','appkey='.$appkey.'&random='.$strRand.'&time='.$strTime);
        $param['title'] ='';
        $param['text'] ='您好，您的验证码是{1},请于10分钟内输入正确的验证码';
        $param['remark'] ='';
        $param['type'] =0;
        $url ='https://yun.tim.qq.com/v5/tlssmssvr/add_template?sdkappid='.$appid.'&random='.$strRand;
        $param =json_encode($param,JSON_UNESCAPED_UNICODE);
        $ch =curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$param);

        $res =curl_exec($ch);
        if(!$res){
            //return curl_error($ch);
            $err =curl_error($ch);
            echo $err;
        }else{
            $res =json_decode($res,true);
            if($res['result'] == 0){
                //return $res['data']['id'];
                $id =$res['data']['id'];
                echo $id ;
            }else{
                return false;
            }
        }

    }

    function percentEncode($str)
    {
        // 使用urlencode编码后，将"+","*","%7E"做替换即满足ECS API规定的编码规范
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    //云之讯服务
    function _sendUcpassSms($to){
        require_once VENDOR_PATH . 'Ucpaas.php';
        //初始化必填
        $options['accountsid']=$this->config['accountSid'];
        $options['token']=$this->config['authToken'];
        $ucpass = new \Ucpaas($options);
        //短信验证码（模板短信）,默认以65个汉字（同65个英文）为一条（可容纳字数受您应用名称占用字符影响），超过长度短信平台将会自动分割为多条发送。分割后的多条短信将按照具体占用条数计费。
        $appId = $this->config['appId'];
        $templateId = (int)($this->config['TemplateId']);
        $param[] = rand(1111,9999);
        $param[]= 60; // $this->config['expire'];
        $is_lock = smsLock($to);
        if($is_lock){
            $resStr = $ucpass->templateSMS($appId,$to,$templateId,implode(',',$param));
            $res = json_decode($resStr,true);
        }else{
            $result['result'] = 0;
            $result['msg'] = "获取验证码太频繁";
            return $result;
        }

        if($res['resp'] && $res['resp']['respCode']=="000000"){
            $data['phone'] = $to;
            $data['plat_type'] = $this->config['type'];
            //$data['from_type'] = $from_type;
            $data['code'] = $param[0];
            $data['status'] = 0;
            $data['smsId'] = $res['resp']['respCode']['smsId'];
            $data['cTime'] = time();
            $this -> add($data);
            $result['result'] = 1;
            $result['msg'] = "发送成功";
        }else{
            $result['result'] = 0;
            $result['msg'] = "发送失败";
        }
        return $result;
    }

}
